<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use mysql_xdevapi\Exception;

class GamesController extends Controller
{

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:admin');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //查询用户游戏数据
        $userGameData = DB::table('game_data')
            ->where(function ($query) {
                $query->orWhere('server_name', 'like', '%' . @$_GET['search'] . '%');
                $query->orWhere('server_ip', 'like', '%' . @$_GET['search'] . '%');
                $query->orWhere('open_time', 'like', '%' . @$_GET['search'] . '%');
                $query->orWhere('network', 'like', '%' . @$_GET['search'] . '%');
                $query->orWhere('introduction', 'like', '%' . @$_GET['search'] . '%');
                $query->orWhere('qq', 'like', '%' . @$_GET['search'] . '%');
                $query->orWhere('consume', 'like', '%' . @$_GET['search'] . '%');
                $query->orWhere('release_date', 'like', '%' . @$_GET['search'] . '%');
                $query->orWhere('publisher', 'like', '%' . @$_GET['search'] . '%');
            })
            ->orderBy('is_top', 'desc')
            ->orderBy('id', 'desc')
            ->paginate(15)
            ->withPath('?search=' . @$_GET['search'] . '');

        return view('admin.games.index', ['userGameData' => $userGameData]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $dhPlat = $list = DB::table('dh_platform')
            ->orderBy('id', 'desc')
            ->get();
        $tags = DB::table('game_tag')
            ->orderBy('id', 'desc')
            ->get();
        return view('admin.games.create', ['dhPlat' => $dhPlat, 'tags'=>$tags]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */

    public function store(Request $request)
    {
        //验证表单
        $this->validate($request, [
             'server_name' => ['required','string','max:8'],
            'server_ip' => ['required','string','max:8'],
            'open_time' => ['required','date','max:20'],
            'introduction' => ['required','string','max:20'],
            'count' => ['required','numeric'],
            'url' => ['required','string','max:50'],
            'server_list' => ['array'],
            'is_top' => ['required','numeric'],
            'image' => [''],
            'money' => ['required'],
            'login_down' => [''],
            'kf_url' => [''],
            'is_all_day' => ['int'],
            'is_every_day' => ['required', 'int'],
            'stars' => ['required', 'int'],
            // 'is_tq' => ['required', 'int'],
            // 'is_rm' => ['required', 'int'],
            'is_gs' => ['required', 'int'],
            // 'is_draw' => ['required', 'int'],
            'area_code' => ['string'],
            'dh_plat_id' => ['int'],
            'tags' => [''],
            'extend_url' => [''],
            // 'is_mobile' => ['required', 'int'],
            'is_tops' => ['required', 'int'],
            'is_bilitype' => ['required', 'int'],
            'technician' => ['required', 'string']
        ]);
        // 处理推荐位置
        if ($request->is_top > 0) {
            // 将其他值为零
            DB::table('game_data')->where('is_top', $request->is_top)->update(['is_top' => 0]);
        }
        // 处理是否每天
        if ($request->is_every_day != 1) {
            // 处理是否全天
            if ($request->is_all_day == 1) {
                $request->open_time = date('Y-m-d', strtotime($request->open_time)) . ' 23:59:59';
            }
        }
        DB::beginTransaction();
        try {
            //写入添加的游戏
            $gameId = DB::table('game_data')->insertGetId([
                'server_name' => $request->server_name,
                'server_ip' => $request->server_ip,
                'open_time' => $request->open_time,
                'introduction' => $request->introduction,
                'url' => $request->url,
                'count' => $request->count,
                'audit' => 1,
                'consume' => 0,
                'publisher' => Auth::user()->username,
                'release_date' => date('Y-m-d H:i:s'),
                'type' => '',
                'is_top' => $request->is_top,
                'image' => $request->image,
                'money' => $request->money,
                'login_down' => $request->login_down ?? '',
                // 'kf_url' => $request->kf_url ?? '',
                'kf_url' => $request->login_down ?? '',
                'is_all_day' => $request->is_all_day,
                'is_every_day' => $request->is_every_day,
                'stars' => $request->stars,
                // 'is_tq' => $request->is_tq,
                // 'is_rm' => $request->is_rm,
                'area_code' => $request->area_code,
                'dh_plat_id' => $request->dh_plat_id,
                'create_time' => date('Y-m-d H:i:s'),
                'url_json' => $request->extend_url,
                // 'is_mobile' => $request->is_mobile,
                'is_gs' => $request->is_gs,
                // 'is_draw' => $request->is_draw,
                'is_tops' => $request->is_tops,
                'is_bilitype' => $request->is_bilitype,
                'technician' => $request->technician,
            ]);

            if (!$gameId) {
                throw new \Exception("发布失败");
            }

            // 写入服务器信息
            if (!empty($request->server_list) && $gameId) {
                foreach ($request->server_list as $item) {
                    $res = DB::table('game_server')->insert([
                        'game_id' => $gameId,
                        'server_name' => $item['name'],
                        'open_server_time' => $item['date']
                    ]);
                    if (!$res) {
                        throw new \Exception("服务器写入失败");
                    }
                }
            }
            // 标签信息
            if (is_array($request->tags) && count($request->tags)) {
                foreach ($request->tags as $id) {
                    $res = DB::table('game_tag_join')->insert(['game_id'=>$gameId, 'tag_id'=>$id]);
                    if (!$res) {
                        throw new \Exception("写入标签失败");
                    }
                }
            }
            DB::commit();
            return response()->json(['message' => '发布成功。', 'success' => 'true']);
        }catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => $e->getMessage(), 'success' => 'false']);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //查询游戏数据信息
        $userGameDataInfo = DB::table('game_data')
            ->where('id', $id)
            ->first();
        // 查询游戏服务器信息
        $serverInfo = DB::table('game_server')
            ->where('game_id', $id)
            ->paginate(200);
        $dhPlat = $list = DB::table('dh_platform')
            ->orderBy('id', 'desc')
            ->get();
        $tags = DB::table('game_tag')
            ->orderBy('id', 'desc')
            ->get();
        $gameTags = DB::table('game_tag_join')
            ->where('game_id', $id)
            ->pluck('tag_id')->toArray();

        return view('admin.games.edit',[
            'userGameDataInfo'=>$userGameDataInfo,
            'serverInfo' => $serverInfo,
            'dhPlat' => $dhPlat,
            'tags' => $tags,
            'gameTags' => $gameTags,
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //验证表单
        $this->validate($request, [
            'server_name' => ['required','string','max:8'],
            'server_ip' => ['required','string','max:8'],
            'open_time' => ['required','date','max:20'],
            'introduction' => ['required','string','max:20'],
            'count' => ['required','numeric'],
            'url' => ['required','string'],
            'is_top' => ['required','numeric'],
            'image' => ['string'],
            'money' => ['required', 'string'],
            'login_down' => [''],
            'kf_url' => [''],
            'is_all_day' => ['int'],
            'is_every_day' => ['required', 'int'],
            'stars' => ['required', 'int'],
            'is_tq' => ['required', 'int'],
            'is_rm' => ['required', 'int'],
            'is_draw' => ['required', 'int'],
            'area_code' => ['string'],
            'dh_plat_id' => ['int'],
            'is_gs' => ['required', 'int'],
            'tags' => [''],
            'extend_url' => [''],
            'is_mobile' => ['required', 'int'],
            'is_bilitype'=> ['required', 'int'],
            'is_tops'=> ['required', 'int'],
            'technician' => ['required', 'string'],
        ]);

        // 处理推荐位置
        if ($request->is_top > 0) {
            // 将其他值为零
            DB::table('game_data')->where('is_top', $request->is_top)->update(['is_top' => 0]);
        }
        // 处理是否每天
        if ($request->is_every_day != 1) {
            // 处理是否全天
            if ($request->is_all_day == 1) {
                $request->open_time = date('Y-m-d', strtotime($request->open_time)) . ' 23:59:59';
            }
        }

        DB::beginTransaction();
        try {
            //更新游戏信息
            DB::table('game_data')
                ->where('id', $id)
                ->update([
                    'server_name' => $request->server_name,
                    'server_ip' => $request->server_ip,
                    'open_time' => $request->open_time,
                    'network' => $request->network ?? '',
                    'introduction' => $request->introduction,
                    'qq' => $request->qq ?? '',
                    'count' => $request->count,
                    'url' => $request->url,
                    'is_top' => $request->is_top,
                    'image' => $request->image,
                    'money' => $request->money,
                    'login_down' => $request->login_down ?? '',
                    'kf_url' => $request->login_down ?? '',
                    // 'kf_url' => $request->kf_url ?? '',
                    'is_all_day' => $request->is_all_day,
                    'is_every_day' => $request->is_every_day,
                    'stars' => $request->stars,
                    'is_tq' => $request->is_tq,
                    'is_rm' => $request->is_rm,
                    'area_code' => $request->area_code,
                    'dh_plat_id' => $request->dh_plat_id,
                    'url_json' => $request->extend_url,
                    'is_mobile' => $request->is_mobile,
                    'is_bilitype' => $request->is_bilitype,
                    'is_gs' => $request->is_gs,
                    'is_draw' => $request->is_draw,
                    'is_tops' => $request->is_tops,
                    'technician' => $request->technician,
                ]);
            // 标签信息
            DB::table('game_tag_join')->where('game_id', $id)->delete();
            if (is_array($request->tags) && count($request->tags)) {
                foreach ($request->tags as $tid) {
                    $res = DB::table('game_tag_join')->insert(['game_id'=>$id, 'tag_id'=>$tid]);
                    if (!$res) {
                        throw new \Exception("写入标签失败");
                    }
                }
            }
            DB::commit();
            return response()->json(['message' => '编辑成功。', 'success' => 'true']);
        }catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => $e->getMessage(), 'success' => 'false']);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {

        DB::table('game_data')
            ->whereIn('id', explode(',', $id))
            ->delete();

        DB::table('game_server')
            ->whereIn('game_id', explode(',', $id))
            ->delete();

        return response()->json(['message' => '删除成功！', 'success' => 'true']);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function addServer(Request $request)
    {
        //验证表单
        $this->validate($request, [
            'server_name' => ['required','string','max:50'],
            'open_server_time' => ['required','string'],
            'game_id' => ['required','int'],
        ]);

        DB::table('game_server')->insert([
            'game_id' => $request->game_id,
            'server_name' => $request->server_name,
            'open_server_time' => $request->open_server_time
        ]);

        return response()->json(['message' => '发布成功。', 'success' => 'true']);
    }

    public function editServer(Request $request, $id)
    {
        //验证表单
        $this->validate($request, [
            'server_name' => ['required','string','max:50'],
            'open_server_time' => ['required','string'],
        ]);

        DB::table('game_server')->where('id', $id)
            ->update([
                'server_name' => $request->server_name,
                'open_server_time' => $request->open_server_time
            ]);
        return response()->json(['message' => '修改成功。', 'success' => 'true']);
    }

    public function delServer($id)
    {
        DB::table('game_server')
            ->whereIn('id', explode(',', $id))
            ->delete();

        return response()->json(['message' => '删除成功！', 'success' => 'true']);
    }

    /**
     * 图片上传
     * @param Request $request
     * @return array
     */
    public function uploadImg(Request $request)
    {
        if ($request->isMethod('POST')) { //判断文件是否是 POST的方式上传
            $tmp = $request->file('file');
            if ($tmp->isValid()) { //判断文件上传是否有效
                $FileType = $tmp->getClientOriginalExtension(); //获取文件后缀

                $FilePath = $tmp->getRealPath(); //获取文件临时存放位置

                $FileName = date('Y-m-d') . uniqid() . '.' . $FileType; //定义文件名

                Storage::disk()->put($FileName, file_get_contents($FilePath)); //存储文件

                // 发出通知通知其他服务器下载图片

                $this->imgNotice($FileName);
                return $data = [
                    'status' => 0,
                    'path' => $FileName //文件路径
                ];
            }
        }
    }
    // 发送下图片通知
    private function imgNotice($url)
    {
        $domainList = config('domain');
        $curDomain = $_SERVER["HTTP_HOST"];
        foreach ($domainList as $domain) {
            if ($curDomain == $domain) {
                continue;
            }
            Log::info('syncImgPush', ['path'=>'https://'.$curDomain."/uploads/{$url}", 'site'=>"https://{$domain}/admin/notLogin/downloadImg"]);
            $this->curlPost("http://{$domain}/admin/notLogin/downloadImg",["domain" => 'https://'.$curDomain, "url" => "/uploads/{$url}"]);
        }
    }


    private function curlPost($url,$post_data,$header=[])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HEADER, $header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }


    public function showAbnormalExtract()
    {
        return view('admin.games.extract');
    }

    public function getAbnormalExtract(Request $request)
    {
        $unionid = $_GET['union_id'] ?? '';
        $gameData = $_GET['game_data'] ?? '';
        $list = DB::table('game_abnormal_extract')->orderBy('id', 'desc');
        if ($unionid) {
            $list = $list->where('unionid', $unionid);
        }
        if ($gameData) {
            $list = $list->where('game_data','like', "%{$gameData}%");
        }
        $list = $list->paginate(10);
        return successResp($list);
    }
}
